<?php
/**
 * 快递100 递模板请求
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-04
 * Time: 14:55
 */

namespace App\Libs\Contracts\Express;


use App\Libs\Contracts\ExpressInterface;

class Kuaidimpl implements ExpressInterface
{
    private  $key = "mknpnkqW5835";
    private  $customer = "2D854C81E053626597310CC9FE15A6DF";
    private  $url='http://poll.kuaidi100.com/poll/query.do';

    /**
     *
     * @param $e_code 快递名 拼音
     * @param $shipping_code 快递单号
     * @return mixed
     */
    private function get($e_code, $shipping_code)
    {
        //参数设置
        $post_data = array();
        $post_data["customer"] = $this->customer;
        $post_data["param"] = '{"com":'."\"$e_code\"".',"num":'."$shipping_code".'}';
        $post_data["sign"] = md5($post_data["param"].$this->key.$post_data["customer"]);
        $post_data["sign"] = strtoupper($post_data["sign"]);
        $o="";
        foreach ($post_data as $k=>$v)
        {
            $o.= "$k=".urlencode($v)."&";		//默认UTF-8编码格式
        }
        $post_data=substr($o,0,-1);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL,$this->url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        $data = str_replace("\&quot;",'"',$result );
        $data = json_decode($data,true);
        return $data;
    }

    /**
     * app("kuaidi")->getData("tiantian","667281147218");
     *获取快递信息
     * @param $e_code 快递名 拼音
     * @param $shipping_code 快递单号
     * @return mixed  $data['data']  time  ftime context
     */
    public function getData($e_code, $shipping_code)
    {
        $result = $this->get($e_code,$shipping_code);

        if($result['message'] == 'ok'){
            $data['state'] = str_replace(array(6,5,4,3,2,1,0),array("退回","派件","签收","疑难","揽件","在途"),$result['state']);
            $data['data'] = $result['data'];
            $data['data'] = array_reverse($data['data']);
            return $data;
        }
        return [
            'result'=>false,
            'returnCode'=>400,
            "message"=>''
        ];

    }


}